'use strict';
/*
 * date@2018-07-10
 * author@杨道泉
 * define@本插件用于通用读取店铺内的商品
 * 用法：<GoodsItems nick={window.info.user_nick} showDepot={false} maxSelect={1} getSelectItems={this.getSelectItems.bind(this)}/>
 * nick: 店铺用户名
 * showDepot：是否显示仓库中的商品
 * maxSelect：最多选择几个商品
 * getSelectedItems：获取已选择的商品列表，包含title\pic_url\num_iid三个参数。
 * selectedItems:设置已经被选择的商品
 */
import React,{PropTypes} from 'react'; 
import {Select,Tab,Tag,Loading,Pagination,Search,Dialog} from 'qnui';
import { Row, Col } from 'qnui/lib/grid';
import classnames from 'classnames';
import {ajax } from 'utils/index';
import './index.scss';
const TabPane = Tab.TabPane;
	
class GoodsItems extends React.Component {

	constructor(props) {
        super(props);
        this.state = {
        		items:[],
        		seller_cats:[],
        		is_onsale:true,
        		q:"",
        		total_results:0,
        		page:1,
        		pagesize:10,
        		selected_items:[],
        		dialogVisible:false,
        		showTabEx:true,
           };
    }
	componentWillMount(){
		this.getItemsOnSale({
			page:1,
			pagesize:10,
			cids:"",
			q:""
		});
		this.getSellerCats({
			nick:this.props.nick
		});
	}
	componentWillReceiveProps(nextProps){

	}
	componentDidUpdate(){

	}
	componentDidMount(nextProps){
		this.setState({selected_items:this.props.selectedItems?this.props.selectedItems:[]});
	}
	getItemsOnSale(params){
		this.setState({is_onsale:true});
		if(window.workbench){
			//千牛环境执行创建折扣,含有workbench参数为千牛环境
			  window.QN.top.invoke( {
					cmd : 'taobao.items.onsale.get',
					param : params,
					method:"post",
					success : function(rsp, cmd, param) {
						console.log(rsp,param);
					},
					error : function(msg, cmd, param) {
						console.log(msg,param);
					}
				} );
		}else{
			ajax({
			  api: 'getItemsOnSale',
			  method: 'GET',
			  data:params
			},(json) => {
				if(json.total_results>0){
					if(!(json.items.item instanceof Array)){
						json.items.item = Array(json.items.item);
					}
				}else{
					json.items={item:[]};
				}
				this.setState({
					  items:json.items.item,
					  total_results:parseInt(json.total_results),
					  page:params.page,
					  pagesize:params.pagesize,
					  cids:params.cids,
					  q:params.q
					});
			},(json) =>{
				const login = (json.code==210);
				this.setState({
					message:json.msg+(json.sub_msg?json.sub_msg:""),
					loginFalse:login,
					showErrorDialog:true
				});
			});
			
		}
	}
	getItemsIndepot(params) {
		this.setState({is_onsale:false});
			if(window.workbench){
				//千牛环境执行创建折扣,含有workbench参数为千牛环境
				  window.QN.top.invoke( {
						cmd : 'taobao.items.inventory.get',
						param : params,
						method:"post",
						success : function(rsp, cmd, param) {
							console.log(rsp,param);
						},
						error : function(msg, cmd, param) {
							console.log(msg,param);
						}
					} );
			}else{
				ajax({
				  api: 'getItemsIndepot',
				  method: 'GET',
				  data:params
				},(json) => {
					if(json.total_results>0){
						if(!(json.items.item instanceof Array)){
							json.items.item = Array(json.items.item);
						}
					}else{
						json.items={item:[]};
					}
					
					this.setState({
					  items:json.items.item,
					  total_results:parseInt(json.total_results),
					  page:params.page,
					  pagesize:params.pagesize,
					  cids:params.cids,
					  q:params.q
					});
				},(json) =>{
					const login = (json.code==210);
					this.setState({
						message:json.msg+(json.sub_msg?json.sub_msg:""),
						loginFalse:login
					});
				});
				
			}
		}

/*
 * @params {nick："用户昵称"}
 */
getSellerCats(params){
		if(window.workbench){
			//千牛环境执行创建折扣,含有workbench参数为千牛环境
			  window.QN.top.invoke( {
					cmd : 'taobao.sellercats.list.get',
					param : params,
					method:"post",
					success : function(rsp, cmd, param) {
						console.log(rsp,param);
					},
					error : function(msg, cmd, param) {
						console.log(msg,param);
					}
				} );
		}else{
			ajax({
			  api: 'getSellerCats',
			  method: 'GET',
			  data:params
			},(json) => {
				if(json.seller_cats && !(json.seller_cats.seller_cat instanceof Array)){
					json.seller_cats.seller_cat = Array(json.seller_cats.seller_cat);
				}
				this.setState({
				  seller_cats:json.seller_cats.seller_cat
				});
			},(json) => {
				const login = (json.code==210);
				this.setState({
					message:json.msg+(json.sub_msg?json.sub_msg:""),
					loginFalse:login
				})
			});
		}
	}
onCatChange(cat_id){
	if(this.state.is_onsale){
		this.getItemsOnSale({
				page:this.state.page,
				pagesize:this.state.pagesize,
				cids:cat_id,
				q:this.state.q
		});
	}else{
		this.getItemsIndepot({
			page:this.state.page,
			pagesize:this.state.pagesize,
			cids:cat_id,
			q:this.state.q
		});
	}
}
onSearchItem(key){
	this.setState({q:key.key});
	if(this.state.is_onsale){
		this.getItemsOnSale({
				page:this.state.page,
				pagesize:this.state.pagesize,
				cids:this.state.cids,
				q:key.key
		});
	}else{
		this.getItemsIndepot({
			page:this.state.page,
			pagesize:this.state.pagesize,
			cids:this.state.cids,
			q:key.key
		});
	}
}
onTabChange(key){
	this.setState({is_onsale:key=="onSale",showTabEx:true});
	switch(key){
		case "onSale":
			this.getItemsOnSale({
					page:this.state.page,
					pagesize:this.state.pagesize,
					cids:this.state.cids,
					q:this.state.q
			});
			break;
		case "inDepot":
			this.getItemsIndepot({
				page:this.state.page,
				pagesize:this.state.pagesize,
				cids:this.state.cids,
				q:this.state.q
			});
			break;
		case "onSelected":
			this.setState({items:this.state.selected_items,total_results:0,showTabEx:false});
			break;
	}
}
onPageChange(page){
	this.setState({page:page});
	if(this.state.is_onsale){
		this.getItemsOnSale({
				page:page,
				pagesize:this.state.pagesize,
				cids:this.state.cids,
				q:this.state.q
		});
	}else{
		this.getItemsIndepot({
			page:page,
			pagesize:this.state.pagesize,
			cids:this.state.cids,
			q:this.state.q
		});
	}
}
onSelectItem(item){
	const selected = this.state.selected_items;

	let has=false;
	selected.map((s_item,key)=>{
		if(s_item.num_iid==item.num_iid){
			has=true;
			selected.splice(key,1);
		}
	});
	
	if(selected.length>=this.props.maxSelect){
		this.setState({dialogVisible:true});
		return;
	}
	
	if(!has){
		selected.push(item);
	}
	this.setState({selected_items:selected});
	this.props.getSelectItems(selected);
}
onDialogClose(){
	this.setState({dialogVisible:false});
}
    render() {
    	   const loading = this.state.items.length==0?<div>没有任何商品...</div>:"";
    	   const items = this.state.items.map((item,key)=>{
    		   								let selected_class_name = "";
    		   								this.state.selected_items.map(s_item=>{
    		   										if(item.num_iid==s_item.num_iid){
    		   											selected_class_name="item-selected"
    		   										    }
    		   								    });
												return <div key={key} className={"item "+selected_class_name} onClick={this.onSelectItem.bind(this,item)}>
												<div className="item-pic"><img src={item.pic_url+"_100x100"} /></div>
												<div className="item-title">{item.title}</div>
											 </div>
								});

    	   const depot = this.props.showDepot?<TabPane tab="仓库中的商品" key="inDepot">
												<Row type="wrap"  justify="start"  style={{maxHeight:"400px",overflowY:"auto"}}>
												{loading}
												{
													items
												}
												</Row>
											   </TabPane>
											   :"";
		  const extraContent=this.state.showTabEx?<Row type="wrap"  justify="start" >
											<Select placeholder="选择类别" onChange={this.onCatChange.bind(this)}>
													<Option value="0">所有类别</Option>
													{
														this.state.seller_cats.map((cat,key)=>{
															 return (<Option key={key} value={cat.cid}>{cat.name}</Option>);
														})
													}
										    </Select>
								    	&nbsp;
								    <Search
								        type="搜索"
								        inputWidth={200}
								        placeholder="输入关键字"
								    	onSearch={this.onSearchItem.bind(this)}/>
									</Row>:"";
        return (
        	 <div>
        			<Dialog visible={this.state.dialogVisible}
		                onOk={this.onDialogClose.bind(this)}
		                closable="esc,mask,close"
		                onCancel={this.onDialogClose.bind(this)}
		                onClose={this.onDialogClose.bind(this)} title="注意">
		            <h3>选择商品出错！你最多选择{this.props.maxSelect}个商品！</h3>
		        </Dialog>
				<Tab onChange={this.onTabChange.bind(this)} tabBarExtraContent={extraContent}>
					<TabPane tab="出售中的商品" key="onSale">
						<Row type="wrap"  justify="start"  style={{maxHeight:"400px",overflowY:"auto"}}>
						{loading}
						{
							items
						}
						</Row>
				   </TabPane>
				   {
					   depot
				   }
				   <TabPane tab="已选择的商品" key="onSelected">
					<Row type="wrap"  justify="start"  style={{maxHeight:"400px",overflowY:"auto"}}>
					{loading}
					{
						items
					}
					</Row>
			   </TabPane>
				</Tab>

				<Row>
					<Pagination defaultCurrent={1} total={this.state.total_results} pageSize={this.state.pagesize} onChange={this.onPageChange.bind(this)} />,
				</Row>
			</div>
        );
    }
    
}
export default GoodsItems;